/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-16 Time: 17:25
 *
 * 新建报修工单 => 选择
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    TouchableOpacity,
    Text,
    ScrollView, BackHandler, Platform, TextInput, Modal, Linking, Clipboard
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from "./RepairWorkOrderChooseConsumablesScreen.Style";
import {FONT_COLOR_SUB_TITLE,COLOR_GRAY_LINE} from "../../../../constant/PHColors";
import AntDesign from "react-native-vector-icons/AntDesign";
import {SCREEN_WIDTH} from "../../../../constant/PHScreen"
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import {retrieveMaterial} from "./Actions";
import PropTypes from "prop-types";

class RepairWorkOrderChooseConsumablesScreen extends Component {

    static propTypes = {
        closeBack:PropTypes.func,
        returnBack:PropTypes.func,
    }

    //构造
    constructor(props) {
        super(props);

        this.state = {
            materialArr:[], //数据源
            modalVisible:false,
            classVisible:true,
            searchVisible:false,
            chooseModalVisible:false,
            chooseBalance:0,
            chooseSn:'',
            chooseMsg:{},
            textInputNum:'1',
            materialLevel:1, //菜单级数
            materialSn:'',//菜单Sn码
            menuArr:[{"name":"材料","sn":"","level":0}],//菜单索引（第一行）
            searchText:'',//查询内容
            textInputLeftBtnColor:COLOR_GRAY_LINE, //左边按钮颜色
        };
    };

    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onRetrieveMaterial !== this.props.onRetrieveMaterial && nextProps.onRetrieveMaterial.fetchStatus === FetchStatus.Success) {
            let materialArr = nextProps.onRetrieveMaterial.DATA;
            this.setState({
                materialArr:materialArr,
            })
        }
    }

    componentDidMount(): void {
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":""},"where":{}};
        dispatch(retrieveMaterial(JSON.stringify(str)))
    }

    render() {
        return (
            <SafeAreaView style={{flex: 1}}>
                <View style={styles.container}>
                    <View style={styles.searchBox}>
                        <AntDesign name={'search1'} size={17} style={{color: FONT_COLOR_SUB_TITLE}}/>
                        <TextInput style={styles.inputText}
                                   keyboardType='web-search'
                                   placeholder='搜索'
                                   onChangeText={text => {
                                       this._search(text)
                                   }}
                        />
                    </View>
                </View>
                <View  style={{height: 40, flexDirection: 'row',backgroundColor:'#e8e8e8',width:SCREEN_WIDTH,borderBottomColor:'#e8e8e8',borderBottomWidth: 1,}}>
                    {
                        this.state.menuArr.map((item, index) => {
                            return this._menuRender(item, index)
                        })
                    }
                </View>
                {
                    this.state.classVisible && (
                        <ScrollView style={{flex: 1}}>
                            {
                                this.state.materialArr.map((item, index) => {
                                    return this._materialRender(item, index)
                                })
                            }
                        </ScrollView>
                    )
                }
                {
                    this.state.modalVisible && (
                        <ScrollView style={{flex: 1,backgroundColor: 'rgba(255, 255, 255, 1)',}}>
                            {
                                this.state.materialArr.map((item, index) => {
                                    let materialSnLength = this.state.materialSn.length;
                                    if(parseInt(item.level)===this.state.materialLevel&&this.state.materialSn===item.sn.substring(0,materialSnLength)){
                                        return this._areaModalRender(item, index)
                                    }
                                })
                            }
                        </ScrollView>
                    )
                }
                {
                    this.state.searchVisible && (
                        <ScrollView style={{flex: 1}}>
                            {
                                this.state.materialArr.map((item, index) => {
                                    console.log(JSON.stringify(item))
                                    return this._searchRender(item, index)
                                })
                            }
                        </ScrollView>
                    )
                }

                {/*选择*/}
                <Modal
                    visible={this.state.chooseModalVisible}
                    //显示是的动画默认none
                    //从下面向上滑动slide
                    //慢慢显示fade
                    animationType = {'none'}
                    //是否透明默认是不透明 false
                    transparent = {true}
                    //关闭时调用
                    onRequestClose={()=> this.onRequestClose()}
                >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                        this.onRequestClose();
                    }}>
                        <View style={styles.modalContainer}>
                            <View style={styles.modalBox} >
                                <TouchableOpacity activeOpacity={1} onPress={()=>{
                                }}>
                                    <View style={styles.modalTitle}>
                                        <Text style={styles.modalTitleTextNum}>
                                            出仓（库存：{this.state.chooseBalance}）
                                        </Text>
                                    </View>
                                    <View style={styles.modalCenter}>
                                        <AntDesign name={'minuscircle'} onPress={()=>{
                                            let num = Number(this.state.textInputNum)-1;
                                            if(num>0){
                                                if(num===1){
                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:COLOR_GRAY_LINE})
                                                }else{
                                                    this.setState({textInputNum : num.toString(),textInputLeftBtnColor:FONT_COLOR_SUB_TITLE})
                                                }
                                            }
                                        }} size={25} style={{color: this.state.textInputLeftBtnColor}}/>
                                        <TextInput style={styles.modalInput}
                                                   keyboardType='numeric'
                                                   textAlign='center'
                                                   onChangeText={text => {
                                                       if(Number(text)<0){
                                                           text = '1'
                                                       }
                                                        this.setState({
                                                            textInputNum : text,
                                                        })
                                                   }}
                                                   defaultValue={this.state.textInputNum}
                                        />
                                        <AntDesign name={'pluscircle'} onPress={()=>{
                                            let num = Number(this.state.textInputNum)+1;
                                            this.setState({
                                                textInputNum : num.toString(),
                                                textInputLeftBtnColor:FONT_COLOR_SUB_TITLE,
                                            })
                                        }} size={25} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                    </View>
                                    <View style={styles.modalBottom}>
                                        <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                            this.setState({
                                                chooseModalVisible:false,
                                                textInputLeftBtnColor:COLOR_GRAY_LINE,
                                                textInputNum:'1',
                                            })
                                        }}>
                                            <View style={styles.modalBottomLeft}>
                                                <Text style={styles.modalBottomLeftText}>
                                                    取消
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                        <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                            this.state.materialLevel=1;//菜单级数
                                            this.state.materialSn = '';//菜单Sn码
                                            let returnJson = {};
                                            returnJson.sn = this.state.chooseSn;
                                            returnJson.quantity = this.state.textInputNum;
                                            let chooseMsg = this.state.chooseMsg;
                                            for(let q in chooseMsg){
                                                returnJson[q] = chooseMsg[q]
                                            }
                                            this.props.returnBack(returnJson)
                                        }}>
                                            <View style={styles.modalBottomRight}>
                                                <Text style={styles.modalBottomRightText}>
                                                    确定
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
            </SafeAreaView>
        )
    };

    onBackAndroid = () =>{
        this.state.materialLevel--;
        if(this.state.materialLevel===0){
            // getStore().dispatch(NavigationActions.back());
            // return false;
            this.props.closeBack();
            return true;
        }else if(this.state.materialLevel===1){
            this.state.materialSn = this.state.materialSn.split('.').pop();
            this.state.menuArr.pop();
            this.setState({
                modalVisible: false,
                classVisible:true,
                searchVisible:false,
            });
            return true;
        }else if(this.state.materialLevel>1){
            this.state.menuArr.pop();
            let arr = this.state.materialSn.split('.');
            if(arr.length>2){
                arr.pop();
                this.state.materialSn = arr.join('.');
            }else if(arr.length===2){
                arr.pop();
                this.state.materialSn = arr[0];
            }
            this.setState({
                modalVisible: true,
                classVisible:false,
                searchVisible:false,
            });
            return true;
        }
        return true;
    };

    onRequestClose(){
        this.setState({
            chooseModalVisible:false,
        })
    }

    _search(text){
        if(text===""){
            this.state.materialLevel=1;
            this.state.materialSn="";
            this.state.menuArr=[{"name":"材料","sn":"","level":0}];
            this.setState({modalVisible: false,classVisible:true,searchVisible:false,searchText:''});
        }else{
            this.setState({modalVisible: false,classVisible:false,searchVisible:true,searchText:text});
        }
    }

    _searchRender(item, index){
        if( (item.name.indexOf(this.state.searchText.toUpperCase())>-1||item.shortcut.indexOf(this.state.searchText.toUpperCase())>-1 )&& item.node==="I"){
            return(
                <TouchableOpacity key={index} activeOpacity={0.8}  onPress={() => {
                    this.setState({
                        chooseModalVisible:true,
                        chooseBalance:item.balance,
                        chooseSn:item.sn,
                        chooseMsg:item,
                    })
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.fullname}
                            </Text>
                        </View>
                    </View>
                </TouchableOpacity>
            )
        }
    }

    //菜单索引
    _menuRender(item, index){
        if(index===0){
            return(
                <TouchableOpacity activeOpacity={1} key={index}  style={styles.clickButtonStyle} onPress={()=>{
                    this.state.materialLevel=1;
                    this.state.materialSn=item.sn;
                    this.state.menuArr.splice(index+1,this.state.menuArr.length-parseInt(index));
                    this.setState({modalVisible: false,classVisible:true,searchVisible:false,});
                }}>
                    <Text style={{fontSize:20}}>{item.name}</Text>
                </TouchableOpacity>
            )
        }else{
            return(
                <View key={index} style={{flexDirection: 'row',}}>
                    <Text style={{flexDirection:'row',marginTop: 12}}>
                        <AntDesign name={'doubleright'} size={15} style={{color: FONT_COLOR_SUB_TITLE}}/>
                    </Text>
                    <TouchableOpacity activeOpacity={1} style={styles.clickButtonStyle} onPress={()=>{
                        this.state.materialLevel=parseInt(item.level)+1;
                        this.state.materialSn=item.sn;
                        this.state.menuArr.splice(index+1,this.state.menuArr.length-parseInt(index));
                        this.setState({modalVisible: true,classVisible:false,searchVisible:false,});
                    }}>
                        <Text style={{fontSize:20}}>{item.name}</Text>
                    </TouchableOpacity>
                </View>
            )
        }

    };

    //主列表
    _materialRender(item, index){
        if(item.level===1){
            return(
                <TouchableOpacity key={index} activeOpacity={0.8}  onPress={() => {
                    if(item.node==='D'){//有下一级
                        this.state.menuArr.push({"name":item.name,"sn":item.sn,"level":item.level});
                        this.setState({modalVisible: true,classVisible:false,searchVisible:false,});
                        this.state.materialLevel++;
                        this.state.materialSn = item.sn;
                    }else{//没下一级
                        this.setState({
                            chooseModalVisible:true,
                            chooseBalance:item.balance,
                            chooseSn:item.sn,
                            chooseMsg:item,
                        })
                    }
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.name}
                            </Text>
                        </View>
                        {this._level1(item)}
                    </View>
                </TouchableOpacity>
            )
        }
    };

    //模态循环列表
    _areaModalRender(item, index){
        return(
            <View key={index} style={{width:SCREEN_WIDTH, backgroundColor:'black',flexDirection: 'row',flexWrap: 'wrap',height: 55}} >
                <TouchableOpacity  activeOpacity={0.8}  onPress={() => {
                    if(item.node==='D'){//有下一级
                        this.state.menuArr.push({"name":item.name,"sn":item.sn,"level":item.level});
                        this.setState({
                            modalVisible: true,
                            classVisible: false,
                            searchVisible:false,
                        });
                        this.state.materialLevel++;
                        this.state.materialSn = item.sn;
                    }else{//没下一级
                        this.setState({
                            chooseModalVisible:true,
                            chooseBalance:item.balance,
                            chooseSn:item.sn,
                            chooseMsg:item,
                        })
                    }
                }}>
                    <View style={styles.boxBody} >
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.name}
                            </Text>
                        </View>
                        {this._level1(item)}
                    </View>
                </TouchableOpacity>
            </View>
        )

    };

    _level1 = (item) => {
        if(item.node==='D'){
            return(
                <View style={styles.rightBox}>
                    <AntDesign name={'right'} size={17} style={{color: FONT_COLOR_SUB_TITLE}}/>
                </View>
            )
        }else{
            return(
                <View style={styles.rightBox}>
                    <Text style={{color: FONT_COLOR_SUB_TITLE,fontSize:17,}}>
                        ({item.balance})
                    </Text>
                </View>
            )
        }
    };
}

const props = state => {
    return {
        onRetrieveMaterial :state.onRetrieveMaterial,
    }
};

export default RepairWorkOrderChooseConsumablesScreen = connect(props)(RepairWorkOrderChooseConsumablesScreen);
